package com.cntaiping.workutil.test;

import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;


public class HttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);


    public static String httpPost(String url, String body){
        return httpPost(url,body,new HashMap<>());
    }


    public static String httpPost(String url, String body,Map<String,String> requestHeader){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);

            post.setEntity(new StringEntity(body, "UTF-8"));
            //设置请求头
            post.setHeader("Content-Type", "application/json;charset=UTF-8");
            post.setHeader("Accept", "application/json");
            if(!requestHeader.isEmpty()) {
                for (Map.Entry<String, String> e : requestHeader.entrySet()) {
                    post.addHeader(e.getKey(), e.getValue());
                }
            }
            //设置请求体
            StringEntity entity = new StringEntity(body, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            post.setEntity(entity);

            post.setConfig(RequestConfig.custom().setConnectTimeout(12000).setSocketTimeout(12000).setConnectionRequestTimeout(12000).build());
            httpResponse = httpClient.execute(post);
            StatusLine statusLine = httpResponse.getStatusLine();
            String json = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            logger.info("---httpStatus:{}---responseEntity:{}",statusLine.getStatusCode(),json);
            //http返回的状态
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                result = "1";
            }else {
                result = "0";
                logger.error("请求异常,状态码:{}",statusLine.getStatusCode());
            }
        } catch (SocketTimeoutException | ConnectTimeoutException | ConnectException e) {
            /**
             * 这里会捕获到连接超时，无法连接的异常
             */
            result = "2";
            logger.error("连接超时：{}",e.getMessage());
            e.printStackTrace();
        } catch (ClientProtocolException exception){
            /**
             * 这里会捕获到url错误，比如不是http协议等
             */
            result = "4";
            logger.error("url协议错误:{}",exception.getMessage());
            exception.printStackTrace();
        } catch (UnknownHostException e) {
            /**
             * 这里会捕获到未知域名错误
             */
            result = "5";
            logger.error("未知域名错误：{}", e.getMessage());
            e.printStackTrace();
        }catch (IOException e){
            result = "6";
            logger.error("网络io异常：{}",e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                System.out.println("连接关闭异常");
            }
        }
        return result;
    }

    public static Map<String, Object> httpGet(String url) throws Exception {
        Map<String, Object> result = new HashMap<>();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);

            //HandleDateService.add_proxy(httpGet);

            httpGet.setConfig(

                    RequestConfig.custom().setConnectTimeout(12000).setSocketTimeout(12000).setConnectionRequestTimeout(12000).build()
            );

            httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            String json = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            logger.info("get请求状态码:{}", statusCode);
            if ("200".equals(statusCode + "")) {
                result.put("success", true);
            } else {
                result.put("success", false);
            }
            result.put("resultBody",json);
            result.put("code", statusCode);

        } catch (SocketTimeoutException | ConnectTimeoutException | ConnectException e) {
            result.put("success", "false");
            e.printStackTrace();
            logger.error("连接超时：{}",e.getMessage());
        } catch (ClientProtocolException exception){
            result.put("success", "false");
            exception.printStackTrace();
            logger.error("url协议错误:{}",exception.getMessage());
        }catch (UnknownHostException e) {
            /**
             * 这里会捕获到未知域名错误
             */
            result.put("success", "false");
            logger.error("未知域名错误：{}", e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                System.out.println("连接关闭异常");
            }

        }
        return result;
    }
}
